package terminal.ui;

import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import terminal.network.Connection;
import terminal.utility.DataHandler;
import terminal.utility.DataUpdater;
import terminal.utility.Symbol;
import terminal.utility.Utility;

public class MainFrame extends JFrame implements DataHandler {

    private DefaultTableModel tableModel;
    private JTable table;
    private JScrollPane tableScroll;
    private ArrayList<Symbol> symbolList;
    private int selectingRow;
    private int selectingCol;
    private Connection connection;

    public MainFrame() {
        initComponents();
        constructTable();
        symbolList = new ArrayList<>();
        connection = new Connection();
        connection.setReqSymbols(symbolList);
        DataUpdater.getInstance().registerStatusHandler(this);
    }

    private void constructTable() {
        tableModel = new DefaultTableModel();
        tableModel.addColumn("#");
        tableModel.addColumn("Symbol");
        tableModel.addColumn("Status");

        table = new JTable(tableModel) {

            Class[] types = new Class[]{
                java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean[]{
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        };
        table.getTableHeader().setReorderingAllowed(false);
        table.getColumnModel().getColumn(0).setResizable(false);
        table.getColumnModel().getColumn(0).setMaxWidth(25);
        table.getColumnModel().getColumn(2).setPreferredWidth(350);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.addMouseListener(new MouseAdapter() {

            public void mouseReleased(MouseEvent e) {
                rowListener(e);
            }
        });

        tableScroll = new javax.swing.JScrollPane();
        tableScroll.setBounds(12, 58, 450, 330);
        tableScroll.setViewportView(table);
        getContentPane().add(tableScroll);

    }

    @Override
    public void updateStatus(int loc, String status) {
        tableModel.setValueAt(status, loc, 2);
    }

    @Override
    public void updateAll(int loc, String data) {
        if (symbolList.get(loc).isValid()) {
            symbolList.get(loc).getItem().updateAll(data);
        } else {
            symbolList.get(loc).setValid();
            symbolList.get(loc).constructItem(symbolList.get(loc).getSymText(), data);
            Utility.setCenter(symbolList.get(loc).getItem());
        }
    }

    @Override
    public void updateSome(int loc, String data) {
        try {
            symbolList.get(loc).getItem().updateAll(data);
        } catch (NullPointerException e) {
            System.err.println("Never get W before!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            symbolList.get(loc).setValid();
            symbolList.get(loc).constructItem(symbolList.get(loc).getSymText(), data);
            Utility.setCenter(symbolList.get(loc).getItem());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        box = new javax.swing.JTextField();
        addBtn = new javax.swing.JButton();
        viewBtn = new javax.swing.JButton();
        removeBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("FastTrader Terminal");
        setMinimumSize(new java.awt.Dimension(478, 478));
        setResizable(false);
        getContentPane().setLayout(null);

        box.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        box.setText("Enter Symbol . . . . ");
        box.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                boxMousePressed(evt);
            }
        });
        box.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                boxKeyReleased(evt);
            }
        });
        getContentPane().add(box);
        box.setBounds(12, 10, 360, 40);

        addBtn.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        addBtn.setText("ADD");
        addBtn.setFocusable(false);
        addBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBtnActionPerformed(evt);
            }
        });
        getContentPane().add(addBtn);
        addBtn.setBounds(382, 10, 80, 40);

        viewBtn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        viewBtn.setText("View");
        viewBtn.setEnabled(false);
        viewBtn.setFocusable(false);
        viewBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewBtnActionPerformed(evt);
            }
        });
        getContentPane().add(viewBtn);
        viewBtn.setBounds(372, 398, 80, 36);

        removeBtn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        removeBtn.setText("Remove");
        removeBtn.setEnabled(false);
        removeBtn.setFocusable(false);
        removeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeBtnActionPerformed(evt);
            }
        });
        getContentPane().add(removeBtn);
        removeBtn.setBounds(22, 398, 90, 36);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBtnActionPerformed
        String text = box.getText();
        boolean isUnique = true;
        for (Symbol x : symbolList) {
            if (x.getSymText().equals(text)) {
                isUnique = false;
            }
        }
        if (!"".equals(text) && !"Enter Symbol . . . . ".equals(text) && isUnique) {
            Symbol symbol = new Symbol(text);
            symbolList.add(symbol);
            tableModel.addRow(new Object[]{tableModel.getRowCount() + 1, text, "requesting data..."});
            box.setText("");
            connection.getNewQoute(text);
        }else{
            box.setText("");
        }
    }//GEN-LAST:event_addBtnActionPerformed

    private void boxMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_boxMousePressed
        box.setText("");
    }//GEN-LAST:event_boxMousePressed

    private void viewBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBtnActionPerformed
        selectingRow = table.getSelectedRow();
        symbolList.get(selectingRow).getItem().setVisible(true);
        viewBtn.setEnabled(false);
    }//GEN-LAST:event_viewBtnActionPerformed

    private void removeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeBtnActionPerformed
        connection.stopThisQuote(symbolList.get(selectingRow).getSymText());
        symbolList.remove(selectingRow);
        tableModel.removeRow(selectingRow);
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            tableModel.setValueAt(i + 1, i, 0);
        }
        removeBtn.setEnabled(false);
    }//GEN-LAST:event_removeBtnActionPerformed

    private void boxKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_boxKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            String text = box.getText();
            boolean isUnique = true;
            for (Symbol x : symbolList) {
                if (text.equals(x.getSymText())) {
                    isUnique = false;
                }
            }
            if (!"".equals(text) && !"Enter Symbol . . . . ".equals(text) && isUnique) {
                Symbol item = new Symbol(text);
                symbolList.add(item);
                tableModel.addRow(new Object[]{tableModel.getRowCount() + 1, box.getText(), "requesting " + text});
                box.setText("");
                connection.getNewQoute(text);
            } else {
                box.setText("");
            }
        }
    }//GEN-LAST:event_boxKeyReleased

    private void rowListener(MouseEvent e) {
        selectingRow = table.getSelectedRow();
        selectingCol = table.getSelectedColumn();
        System.out.println("Row: " + selectingRow + "| Col: " + selectingCol);
        removeBtn.setEnabled(true);
        if (symbolList.get(selectingRow).isValid()) {
            if (symbolList.get(selectingRow).getItem().isVisible()) {
                viewBtn.setEnabled(false);
            } else {
                viewBtn.setEnabled(true);
            }
        } else {
            viewBtn.setEnabled(false);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addBtn;
    private javax.swing.JTextField box;
    private javax.swing.JButton removeBtn;
    private javax.swing.JButton viewBtn;
    // End of variables declaration//GEN-END:variables
}
